#coding:utf-8

import tkinter as tk
import tkinter.font as tkFont

from PIL import Image, ImageTk
import datetime
import cv2
import os

import ocr_tts 
from paddleocr import PaddleOCR
import mediapipe as mp
import time

import logging

logging.disable(logging.DEBUG)  # 关闭DEBUG日志的打印
logging.disable(logging.WARNING)  # 关闭WARNING日志的打印

class Config:
    def __init__(self) -> None:
        self.enable_mp = True

class App:
    def __init__(self, root):

        self.cnf = Config()

        self.cap = cv2.VideoCapture(1)  
        #self.cap.set(cv2.CAP_PROP_FPS, 30)

        self.current_image = None  # current image from the camera

        #setting title
        self.root = root
        self.root.title("storyteller")
        #setting window size
        width=803
        height=475
        screenwidth = self.root.winfo_screenwidth()
        screenheight = self.root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        self.root.geometry(alignstr)
        self.root.resizable(width=False, height=False)

        self.tk_camera=tk.Label(self.root)
        self.tk_camera["bg"] = "#999999"
        ft = tkFont.Font(family='Times',size=10)
        self.tk_camera["font"] = ft
        self.tk_camera["fg"] = "#333333"
        self.tk_camera["justify"] = "center"
        self.tk_camera["text"] = "摄像头"
        self.tk_camera.place(x=10,y=50,width=555,height=412)

        self.tk_btnStart=tk.Button(self.root)
        self.tk_btnStart["bg"] = "#efefef"
        ft = tkFont.Font(family='Times',size=10)
        self.tk_btnStart["font"] = ft
        self.tk_btnStart["fg"] = "#000000"
        self.tk_btnStart["justify"] = "center"
        self.tk_btnStart["text"] = "开始"
        self.tk_btnStart.place(x=580,y=10,width=92,height=30)
        self.tk_btnStart["command"] = self.start_commond

        self.tk_text=tk.Label(self.root)
        self.tk_text["bg"] = "#ffffff"
        ft = tkFont.Font(family='Times',size=10)
        self.tk_text["font"] = ft
        self.tk_text["fg"] = "#333333"
        self.tk_text["justify"] = "left"
        self.tk_text["anchor"] = "nw"
        self.tk_text["text"] = "识别结果"
        self.tk_text.place(x=580,y=50,width=211,height=409)

        self.tk_btnExit=tk.Button(self.root)
        self.tk_btnExit["bg"] = "#efefef"
        ft = tkFont.Font(family='Times',size=10)
        self.tk_btnExit["font"] = ft
        self.tk_btnExit["fg"] = "#000000"
        self.tk_btnExit["justify"] = "center"
        self.tk_btnExit["text"] = "退出"
        self.tk_btnExit.place(x=690,y=10,width=89,height=30)
        self.tk_btnExit["command"] = self.exit_command

        self.tk_info=tk.Label(self.root)
        ft = tkFont.Font(family='Times',size=10)
        self.tk_info["font"] = ft
        self.tk_info["borderwidth"] = 1
        self.tk_info["relief"] = "solid"
        self.tk_info["fg"] = "#333333"
        self.tk_info["anchor"] = "w"
        self.tk_info["justify"] = "left"
        self.tk_info["text"] = "状态信息..."
        self.tk_info.place(x=10,y=10,width=555,height=30)

        #self.video_loop()
        self.active = False

        self.layout = 'fit'

        # 模型路径下必须含有model和params文件
        self.ocr = PaddleOCR(use_angle_cls=True,
                        use_gpu=False)  # det_model_dir='{your_det_model_dir}', rec_model_dir='{your_rec_model_dir}', rec_char_dict_path='{your_rec_char_dict_path}', cls_model_dir='{your_cls_model_dir}', use_angle_cls=True
        
        # 手指识别
        if self.cnf.enable_mp:
            self.mp_drawing = mp.solutions.drawing_utils
            self.mp_hands = mp.solutions.hands
            self.hands = self.mp_hands.Hands(
                    static_image_mode=False,
                    max_num_hands=1,
                    min_detection_confidence=0.2,
                    min_tracking_confidence=0.2)

    def video_loop(self):
        if self.active:
            """ Get frame from the video stream and show it in Tkinter"""
            #ocr_tts.take_ocr(self.cap, self.ocr, self.display_vedio, self.tk_info)

            pTime = time.time()  
            ocr_tts.take_ocr(self)
            cTime = time.time()
            fps = 1 / (cTime - pTime)
            self.tk_text['text'] = "FPS: {}".format(int(fps))
            self.root.after(10, self.video_loop)

    def start_commond(self):
        print("start camera...")
        
        if self.tk_btnStart["text"] == '开始':
            self.tk_btnStart["text"] ='暂停'
            self.active = True
            self.video_loop()
        else:
            print("pause camera...")
            self.tk_btnStart["text"] = '开始'
            self.active = False

    def exit_command(self):
        print("exit...")
        self.root.destroy()
        self.cap.release() 
        cv2.destroyAllWindows()  
    
    def display_vedio(self, frame, result):
        # cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
        # self.current_image = Image.fromarray(
        #     cv2image)  # convert image for PIL
        # # convert image for tkinter
        # imgtk = ImageTk.PhotoImage(image=self.current_image)
        # self.tk_camera.imgtk = imgtk  # anchor imgtk so it does not be deleted by garbage-collector
        # self.tk_camera.config(image=imgtk)  # show the image    

        canvawidth = int(self.tk_camera.winfo_width())
        canvaheight = int(self.tk_camera.winfo_height())
        sp = frame.shape
        cvheight = sp[0]#height(rows) of image
        cvwidth = sp[1]#width(colums) of image

        if (self.layout == "fill"):
            imgCV = cv2.resize(frame,(canvawidth,canvaheight), interpolation=cv2.INTER_AREA)
        elif(self.layout == "fit"):

            if (float(cvwidth/cvheight) > float(canvawidth/canvaheight)):
                imgCV = cv2.resize(frame,(canvawidth,int(canvawidth*cvheight/cvwidth)), interpolation=cv2.INTER_AREA)
            else:
                imgCV = cv2.resize(frame,(int(canvaheight*cvwidth/cvheight),canvaheight), interpolation=cv2.INTER_AREA)
        else:
            imgCV = frame

        cv2image = cv2.cvtColor(imgCV, cv2.COLOR_BGR2RGBA)
        self.current_image = Image.fromarray(
            cv2image)  # convert image for PIL
        # convert image for tkinter
        imgtk = ImageTk.PhotoImage(image=self.current_image)
        self.tk_camera.imgtk = imgtk  # anchor imgtk so it does not be deleted by garbage-collector
        self.tk_camera.config(image=imgtk)  # show the image    

        self.tk_text['text'] = result


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
